from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import email
import cgi
import logging
import EmailStore
#Wave APIS
from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document
    

class EmailHandler(webapp.RequestHandler):
    #Recieved new email from smtp2web.com
    def post(self):
        sender = self.request.GET.get("from", "")
        logging.debug('sender: %s' % sender)
        recipient = self.request.GET.get("to", "")
        logging.debug('recipient: %s' % recipient)
        logging.debug('message: %s' % self.request.body)
        message = email.message_from_string(self.request.body)
        body = ""
        for part in message.walk():
            if part.is_multipart():
                continue
            #Only Store plain text version of email
            if part.get_content_type() == 'text/plain':
                body += part.get_payload(decode=1)
        # Store Email In Database
        newEmail = EmailStore()
        newEmail.sender = sender
        newEmail.recipient = recipient
        newEmail.subject = message['subject']
        newEmail.message = body
        newEmail.put()

    #Print Emails In Database
    def get(self):
        self.response.out.write('<html><body>')
        emails = db.GqlQuery("SELECT * FROM EmailStore")
        for currEmail in emails:
            self.response.out.write('<b>Sender:</b> %s <br /> <b>Recipient:</b> %s  <br /> <b>Subject:</b> %s <br /> <b>Message:</b> %s  <br /><br />' %
                                    (cgi.escape(currEmail.sender),cgi.escape(currEmail.recipient),cgi.escape(currEmail.subject),cgi.escape(currEmail.message)))
        self.response.out.write('</body></html>')

def main():
    application = webapp.WSGIApplication(
                                     [('/new_email', EmailHandler)],
                                     debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
